<template>
  <m-window-frame
    :title="title"
    style="height: 100%"
    class="v-track-editor-window"
    @cancel="handleCancel"
    @ok="handleSave"
  >
    <div class="v-track-editor-window-container">
      <AttrTips
        class="_main-title g-flex-0"
        :type="attrType"
      ></AttrTips>
      <div class="form-container">
        <div
          v-for="(item, index) in ruleForm"
          :key="item.id"
          style="margin-top: 14px"
        >
          <div class="title g-ai-c">
            <span>轨迹点{{ index + 1 }}</span>
            <img
              v-if="index > 0"
              src="statics/arch/icon/delete.svg"
              alt=""
              class="delete-track"
              @click="deleteTrack(index)"
            />
          </div>
          <el-form
            ref="ruleFormRefs"
            :model="item"
            :rules="rules"
            label-width="auto"
            :hide-required-asterisk="true"
          >
            <el-form-item
              label="经度"
              prop="platLon"
            >
              <el-input v-model="item.platLon">
                <template #append>°</template>
              </el-input>
            </el-form-item>
            <el-form-item
              label="纬度"
              prop="platLat"
            >
              <el-input v-model="item.platLat">
                <template #append>°</template>
              </el-input>
            </el-form-item>
            <el-form-item
              label="高度"
              prop="platAlt"
            >
              <el-input v-model="item.platAlt">
                <template #append>m</template>
              </el-input>
            </el-form-item>
            <el-form-item
              label="速度"
              prop="speed"
            >
              <el-input v-model="item.speed">
                <template #append>m/s</template>
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <span
          class="add-track g-ai-c"
          @click="addTrack"
        >
          <img
            src="statics/arch/icon/plus.svg"
            alt=""
            style="margin-right: 3px"
          />
          新增轨迹点
        </span>
      </div>
    </div>
  </m-window-frame>
</template>
<script lang="ts" setup>
import MWindowFrame from "@/common/ipcWindow/WindowFrame.vue";
import { ref, watch, reactive, toRaw } from "vue";
import { Params, CloseData } from "./index";
import { useRoute } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
import { ipcWindowUtil } from "@/mdesign-lib/mdesign-app.umd.js";
import AttrTips from "@/common/attrTip/AttrTip.vue";
import { getUid } from "@/util/common";

interface RuleForm {
  platLon?: number;
  platLat?: number;
  platAlt?: number;
  speed?: number;
  id: string;
  isNew?: boolean;
}

const ruleForm = reactive<RuleForm[]>([]);

const ruleFormRefs = ref<FormInstance[]>([]);

const rules = reactive<FormRules<RuleForm>>({
  platLon: [
    { required: true, message: "请输入经度" },
    { pattern: /^-?\d+(\.\d+)?$/, message: "请输入一个数字" },
    { validator: validateRange, min: -180, max: 180 }
  ],
  platLat: [
    { required: true, message: "请输入纬度" },
    { pattern: /^-?\d+(\.\d+)?$/, message: "请输入一个数字" },
    { validator: validateRange, min: -90, max: 90 }
  ],
  platAlt: [
    { required: true, message: "请输入高度" },
    { pattern: /^\d+(\.\d+)?$/, message: "请输入一个≥0的数字" }
  ],
  speed: [
    { required: true, message: "请输入速度" },
    { pattern: /^\d+(\.\d+)?$/, message: "请输入一个≥0的数字" }
  ]
});
const title = ref("");
const attrType = ref("");

const route = useRoute();
watch(
  () => route.fullPath,
  () => {
    const routeQuery = route.query as unknown;
    const query = routeQuery as Params;
    const defaultTrackData = JSON.parse(query.data || "[]");
    title.value = query.title;
    attrType.value = query.attrType;
    if (defaultTrackData.length) {
      defaultTrackData.forEach(item => {
        ruleForm.push(item);
      });
    } else {
      addTrack();
    }
  },
  { immediate: true }
);

function validateRange(rule: any, value: string, callback: any) {
  console.log(rule, value);
  const num = parseFloat(value);
  const { max, min } = rule;
  if (num < min || num > max) {
    callback(new Error(`请输入${min}到+${max}范围内的数值`));
  } else {
    callback();
  }
}

function addTrack() {
  ruleForm.push({ id: getUid(), isNew: true });
}

const deleteTrack = (index: number) => {
  ruleForm.splice(index, 1);
};

const handleSave = async () => {
  const queue: Promise<boolean>[] = ruleFormRefs.value.map(item => item.validate());

  const valids = await Promise.all(queue);
  if (!valids.every(item => item)) return;
  const data: any[] = [];
  ruleForm.forEach(formData => {
    if (formData.isNew) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      const { id, isNew, ...rest } = formData;
      data.push(rest);
    } else {
      data.push(toRaw(formData));
    }
  });
  handleclose({ success: true, data });
};

function handleclose(data: CloseData) {
  ipcWindowUtil.closeWindow(data);
}
function handleCancel() {
  handleclose({ success: false });
}
</script>
<style lang="scss">
.v-track-editor-window {
  .v-track-editor-window-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    .form-container {
      flex: 1;
      overflow: auto;
      padding: 10px 32px;
      .title {
        line-height: 16px;
        font-weight: 500;
        margin-bottom: 17px;
      }
    }
    .add-track {
      margin-top: 14px;
      cursor: pointer;
      color: #7177cc;
    }
    .delete-track {
      margin-left: 8px;
      cursor: pointer;
    }
    .el-form {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      border-bottom: 1px dashed #e0e0e0;
      padding-bottom: 5px;
    }
    .el-form-item {
      width: 47%;
      height: 32px;
      margin-bottom: 12px;
      .el-form-item__label {
        padding-right: 0;
        line-height: 32px;
        color: #000;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
      .el-form-item__label-wrap {
        margin-right: 15px;
      }
      .el-input-group__append {
        border-radius: 0;
        background: #f2f2f2;
        width: 32px;
        padding: 0;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .el-input__wrapper {
        border: 1px solid rgba(0, 0, 0, 0.15);
        box-shadow: none;
      }
      .el-select {
        width: 100%;
      }
      .el-button {
        border-color: rgba(0, 0, 0, 0.15);
        padding: 8px;
        border-radius: 0;
        &:hover {
          border-color: var(--md-primary-color);
        }
      }
    }
  }
}
</style>
